import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:async';
import 'package:uuid/uuid.dart';

class CryptoRechargeScreen extends StatefulWidget {
  const CryptoRechargeScreen({super.key});

  @override
  State<CryptoRechargeScreen> createState() => _CryptoRechargeScreenState();
}

class _CryptoRechargeScreenState extends State<CryptoRechargeScreen> {
  String selectedCrypto = 'USDT'; // 默认选择比特币
  final TextEditingController _amountController = TextEditingController();
  final TextEditingController _remarkController = TextEditingController();

  final List<Map<String, dynamic>> cryptoList = [
    {'symbol': 'BTC', 'name': '比特币', 'icon': Icons.currency_bitcoin},
    {'symbol': 'ETH', 'name': '以太坊', 'icon': Icons.currency_exchange},
    {'symbol': 'USDT', 'name': 'USDT', 'icon': Icons.attach_money},
  ];

  final String _walletAddress = 'TB2f62SGU7yqtqzL5LCzfH71bA6oXbp9Ff';

  // 添加充值状态
  bool _isRechargeCompleted = false;
  Timer? _checkStatusTimer;

  // 添加订单相关属性
  String? _orderId;
  final String _userWalletId = 'USER_WALLET_ID'; // TODO: 从用户系统获取实际钱包ID

  @override
  void initState() {
    super.initState();
    // 创建充值订单
    _createRechargeOrder();
  }

  @override
  void dispose() {
    _checkStatusTimer?.cancel();
    super.dispose();
  }

  void _startCheckingRechargeStatus() {
    // 每30秒检查一次充值状态
    _checkStatusTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
      _checkRechargeStatus();
    });
  }

  Future<void> _createRechargeOrder() async {
    _orderId = const Uuid().v4();

    try {
      // TODO: 调用后端 API 创建充值订单
      // final response = await http.post(
      //   Uri.parse('${API_BASE_URL}/recharge/create'),
      //   body: {
      //     'orderId': _orderId,
      //     'userWalletId': _userWalletId,
      //     'currency': selectedCrypto,
      //     'amount': _amountController.text,
      //     'walletAddress': _walletAddress,
      //     'remark': _remarkController.text,
      //   },
      // );

      _startCheckingRechargeStatus();
    } catch (e) {
      debugPrint('创建充值订单失败: $e');
    }
  }

  Future<void> _checkRechargeStatus() async {
    if (_orderId == null) return;

    try {
      // 显示加载提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('正在查询充值状态...'),
          duration: Duration(seconds: 1),
        ),
      );

      // TODO: 调用后端API检查充值状态
      // final response = await http.get(
      //   Uri.parse('${API_BASE_URL}/recharge/status/$_orderId'),
      // );

      // 模拟API调用延迟
      await Future.delayed(const Duration(seconds: 1));

      // 模拟充值成功的情况
      setState(() => _isRechargeCompleted = true);
      _showRechargeCompletedDialog();

      // 取消定时器，避免重复查询
      _checkStatusTimer?.cancel();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('查询充值状态失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
      debugPrint('检查充值状态失败: $e');
    }
  }

  void _showRechargeCompletedDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('充值成功'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('已成功充值 ${_amountController.text} $selectedCrypto'),
            if (_remarkController.text.isNotEmpty)
              Text('备注: ${_remarkController.text}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              context.pop(); // 关闭对话框
              context.pop(); // 返回上一页
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.pop(),
        ),
        title: const Text('数字货币充值'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(8.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '选择充值币种',
                style: TextStyle(
                  fontSize: 13.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 4.h),
              _buildCryptoGrid(),
              SizedBox(height: 8.h),
              Text(
                '充值金额',
                style: TextStyle(
                  fontSize: 13.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 4.h),
              TextField(
                controller: _amountController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  hintText: '请输入充值金额',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  suffixText: selectedCrypto,
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                ),
              ),
              SizedBox(height: 8.h),
              _buildQRCodeSection(),
              SizedBox(height: 8.h),
              _buildRechargeNotes(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCryptoGrid() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 8.w,
        mainAxisSpacing: 8.h,
        childAspectRatio: 2.0,
      ),
      itemCount: cryptoList.length,
      itemBuilder: (context, index) {
        final crypto = cryptoList[index];
        final isSelected = crypto['symbol'] == selectedCrypto;

        return InkWell(
          onTap: () {
            setState(() {
              selectedCrypto = crypto['symbol'];
            });
          },
          child: Container(
            decoration: BoxDecoration(
              color: isSelected
                  ? Theme.of(context).primaryColor.withOpacity(0.1)
                  : Colors.grey[100],
              borderRadius: BorderRadius.circular(8.r),
              border: isSelected
                  ? Border.all(color: Theme.of(context).primaryColor)
                  : null,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(crypto['icon'],
                    color: isSelected
                        ? Theme.of(context).primaryColor
                        : Colors.grey),
                SizedBox(height: 4.h),
                Text(
                  crypto['name'],
                  style: TextStyle(
                    color: isSelected
                        ? Theme.of(context).primaryColor
                        : Colors.black,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildQRCodeSection() {
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Column(
        children: [
          Container(
            width: 160.w,
            height: 160.w,
            padding: EdgeInsets.all(4.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: QrImageView(
              data: _walletAddress,
              version: QrVersions.auto,
              size: 112.w,
            ),
          ),
          SizedBox(height: 4.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Text(
                  _walletAddress,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 11.sp),
                ),
              ),
              IconButton(
                icon: Icon(Icons.copy, size: 16.r),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('地址已复制')),
                  );
                },
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
              ),
            ],
          ),
          if (_orderId != null) ...[
            SizedBox(height: 4.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '订单号: ',
                  style: TextStyle(fontSize: 11.sp),
                ),
                Expanded(
                  child: Text(
                    _orderId!,
                    style: TextStyle(fontSize: 11.sp),
                    textAlign: TextAlign.center,
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.copy, size: 16.r),
                  onPressed: () {
                    // TODO: 复制订单号到剪贴板
                  },
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
            SizedBox(height: 4.h),
            TextField(
              controller: _remarkController,
              decoration: InputDecoration(
                hintText: '添加备注信息（选填）',
                hintStyle: TextStyle(fontSize: 11.sp),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(4.r),
                ),
              ),
              style: TextStyle(fontSize: 11.sp),
            ),
          ],
          if (!_isRechargeCompleted) ...[
            SizedBox(height: 4.h),
            ElevatedButton.icon(
              onPressed: _checkRechargeStatus,
              icon: Icon(Icons.refresh, size: 14.r),
              label: Text('查询充值状态', style: TextStyle(fontSize: 12.sp)),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              ),
            ),
          ],
          if (_isRechargeCompleted)
            Container(
              margin: EdgeInsets.only(top: 4.h),
              padding: EdgeInsets.symmetric(vertical: 2.h, horizontal: 8.w),
              decoration: BoxDecoration(
                color: Colors.green[50],
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.check_circle, color: Colors.green, size: 14.r),
                  SizedBox(width: 4.w),
                  Text(
                    '充值已完成',
                    style: TextStyle(
                      color: Colors.green,
                      fontSize: 11.sp,
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildRechargeNotes() {
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: Colors.orange[50],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '充值说明：',
            style: TextStyle(
              fontSize: 11.sp,
              fontWeight: FontWeight.w500,
              color: Colors.orange[800],
            ),
          ),
          Text(
            '1. 请确保充值地址正确\n'
            '2. 最小充值金额: 0.001 ${selectedCrypto}\n'
            '3. 充值到账时间约5-30分钟\n'
            '4. 请勿向上述地址充值其他币种',
            style: TextStyle(
              fontSize: 10.sp,
              color: Colors.orange[800],
              height: 1.2,
            ),
          ),
        ],
      ),
    );
  }
}
